package core

import (
	"dgo/MyProj/PrjHttpUtils"
	"dgo/goutils/utils"
	"dgo/plg/plgbase"
	"dgo/plg/plgbasev0"
	"fmt"
	"gitee.com/ymofen/supervalue"
)

/**
  接收数据处理命令, 废弃了
*/

type CoreCmdCltPlug struct {
	plgbasev0.ProjBaseProduce
	topic   string
	ex      *plgbasev0.InnerEx
	recvlst *utils.SyncCycleList
}

func (this *CoreCmdCltPlug) procJson(json *wrapper.SuperValue) {
	respTopic := json.StringByName("resp-topic", "")
	cmd := json.ValueByName("list")
	if cmd == nil {
		cmd = json
		cmd.RemoveKey("resp-topic")
	}

	n := 0
	cmd.Range(func(key string, val *wrapper.SuperValue) bool {
		_, errcode, err := plgbase.PlgCheckReloadFromJSON(val)
		if err != nil {
			if len(respTopic) > 0 {
				this.ex.SendTopic(respTopic, func(json *wrapper.SuperValue) {
					json.SetKeyValues("errcode", errcode, "msg", err.Error())
				})
			} else {
				utils.Log.WarnTypef(this.PlugId, "处理命令异常:%s", err.Error())
			}

		} else {
			n++
			utils.Log.DebugTypef(this.PlugId, "插件[%s], 数据:%s", val.StringByName("id", ""), val.AsJSONString(false))
		}
		return true
	})

}

/*
*

	{
	   "list":[
	      {}
	   ],
	   "resp-topic":"/响应主题"
	}
*/
func (this *CoreCmdCltPlug) OnRecv(topic string, data interface{}) {
	if json, ok := data.(*wrapper.SuperValue); ok {
		this.recvlst.Push(fmt.Sprintf("[%s]收到配置\n%s", utils.NowString(), json.String()))
		this.procJson(json)
	} else if str, ok := data.(string); ok {
		this.recvlst.Push(fmt.Sprintf("[%s]收到配置\n%s", utils.NowString(), str))
		json, err := wrapper.NewSVFromBuf([]byte(str))
		if err != nil {
			utils.Log.WarnTypef(this.PlugId, "收到非法的命令数据, 非法的JSON格式")
		} else {
			this.procJson(json)
		}
	} else {
		utils.Log.WarnTypef(this.PlugId, "收到非法的命令数据")
	}
	return
}

func (this *CoreCmdCltPlug) OnHttpStatus(rec *PlgHttpRec) (rval interface{}, errcode int, err error) {
	itype := rec.QryAsInt("type", 0)
	if itype == 99 {
		var sb utils.BytesBuilder
		rec.RespW.Write(sb.Bytes())
	} else if itype == 1 {
		rec.ResponseText(fmt.Sprintf("%s\n", utils.NowString()))
		rec.ResponseSyncList(this.recvlst, rec.QryAsString("searchval", ""))
	} else {
		var sb utils.BytesBuilder
		sb.Appendf("now:%s\n", utils.NowString())
		PrjHttpUtils.AppendIndexBody(&sb, "status", "status?type=99")
		PrjHttpUtils.AppendIndexBody(&sb, "history", "status?type=1&searchval=")
		PrjHttpUtils.ResponseBodyHtml(rec.RespW, sb.String())
	}
	return
}

/*
**

	{
	  "id":"core-cmd-recv",
	  "type":"core.cmd",
	  "conf":{
	      "input":{
	        "id":"core-wsex"
	      },
	      "topic":"/cmd/$appuuid$",
	   }
	}
*/
func (this *CoreCmdCltPlug) ReloadConf(conf *wrapper.SuperValue) error {
	if this.recvlst == nil {
		this.recvlst = utils.NewSyncCycleList()
		this.recvlst.ConfigMaxSize(128)
	}
	inputConf := conf.ValueByName("input")
	if inputConf == nil {
		inputConf = conf.ValueByName("ex") // 不在使用
	}
	this.ex.ReloadConf(inputConf)
	conf.CheckExistsStrFunc("topic", func(strv string) {
		if this.topic != strv {
			this.topic = strv
			topic := plgbasev0.ReplacePlaceholder(this.topic)
			this.ex.Subscribe(topic, func(sender interface{}, channelid string, subscribeid interface{}, data interface{}, tag interface{}, isBreak *bool) bool {
				this.OnRecv(topic, data)
				return true
			})
		}
	})

	return nil
}

func (this *CoreCmdCltPlug) OnObjectNotify(sender interface{}, notifytype int, data interface{}) (rval interface{}, err error) {
	if notifytype == utils.NOTIFY_TYPE_SETCONF {
		if conf, ok := data.(*wrapper.SuperValue); ok {
			err = this.ReloadConf(conf)
		} else {
			err = fmt.Errorf("非法的JSON配置")
		}
	} else if notifytype == utils.NOTIFY_TYPE_RELEASE {
		this.ex.Release()
		this.ReleaseFlag = 1

	}
	return
}

func CreateCoreCmdCltPlugFunc(args ...interface{}) (rval interface{}, err error) {
	obj := &CoreCmdCltPlug{}
	if len(args) > 0 {
		if str, ok := args[0].(string); ok {
			obj.PlugId = str
		}
	}
	obj.ex = plgbasev0.NewInnerEx()
	rval = obj
	return
}
